<template>
    <div>
        <el-breadcrumb separator="/" style="padding-bottom:16px" v-if="!publicInfo">
            <el-breadcrumb-item :to="{ path: lastPath }"> {{$t('schoolAdministration.creditRecognition')}}</el-breadcrumb-item>
            <el-breadcrumb-item v-if="mode == 'ADD'">{{$t('schoolAdministration.apply')}}</el-breadcrumb-item>
            <el-breadcrumb-item v-else-if="mode == 'EDIT'">{{$t('schoolAdministration.edit')}}</el-breadcrumb-item>
            <el-breadcrumb-item v-else>{{$t('schoolAdministration.check')}}</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <baseInfo :studentId="studentInfo.studentId"></baseInfo>
            <h1 slot="header">{{$t('schoolAdministration.creditRecognition')}}</h1>
            <h2>{{$t('schoolAdministration.exchangeName')}}</h2>
            <el-form
                label-suffix="："
                :model="applyParams"
                ref="application"
                label-position="right"
                label-width="100px"
                :disabled="mode == 'VIEW'"
            >
                <el-form-item
                    :label="$t('schoolAdministration.exchangeName')"
                    prop="exchangeName"
                    style="padding-left:32px"
                    :rules="[{ required: true, message: $t('schoolAdministration.pleaseSelectExchangeName'), trigger: 'change' }]"
                >
                    <el-select
                        v-model="applyParams.exchangeName"
                        @change="exchangeChange"
                        :placeholder="$t('schoolAdministration.pleaseEnter')"
                        style="width:25%"
                        :disabled="mode == 'AUDIT'"
                        clearable
                    >
                        <el-option
                            v-for="item in options.exchangeList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-row>
                    <el-col span="12">
                        <h2 style="line-height:32px"><span style="color:#F56C6C;margin-right: 4px">*</span>{{$t('schoolAdministration.oldCourseStr')}}</h2>
                    </el-col>
                    <el-col span="12" style="text-align:right" v-if="mode !== 'VIEW' && mode !== 'AUDIT'">
                        <el-button type="primary" @click="addOldCourse">{{$t('schoolAdministration.add')}}</el-button>
                    </el-col>
                </el-row>
                <edu-table :data="applyParams.oldCourseList" :selection="false" :pagination="false" class="course-table">
                    <el-table-column  :label="$t('schoolAdministration.oldCourseStrName')" header-align="center" align="center">
                        <template slot-scope="scope">
                            <el-form-item
                                label-width="0"
                                v-if="!scope.row.status"
                                :prop="`oldCourseList[${scope.$index}].oldCourseName`"
                                :rules="[
                                    {
                                        required: true,
                                        message: $t('schoolAdministration.pleaseOldCourseStrName'),
                                        trigger: ['blur', 'change']
                                    }
                                ]"
                            >
                                <el-input clearable v-model="scope.row.oldCourseName"  :disabled="mode == 'AUDIT'"></el-input>
                            </el-form-item>
                            <span v-else>{{ scope.row.oldCourseName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('schoolAdministration.originalScore')" header-align="center" align="center">
                        <template slot-scope="scope">
                            <el-form-item
                                v-if="!scope.row.status"
                                label-width="0"
                                :prop="`oldCourseList[${scope.$index}].oldCourseScore`"
                                :rules="[
                                    {
                                        required: true,
                                        message: $t('schoolAdministration.pleaseOriginalScore'),
                                        trigger: ['blur', 'change']
                                    }
                                ]"
                            >
                                <el-input
                                    type="number"
                                    min="0"
                                    max="100"
                                    :disabled="mode == 'AUDIT'"
                                    v-model="scope.row.oldCourseScore"
                                ></el-input>
                            </el-form-item>
                            <span v-else>{{ scope.row.oldCourseScore }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('schoolAdministration.originalCredits')" header-align="center" align="center">
                        <template slot-scope="scope">
                            <el-form-item
                                v-if="!scope.row.status"
                                label-width="0"
                                :prop="`oldCourseList[${scope.$index}].oldCredit`"
                                :rules="[
                                    {
                                        required: true,
                                        message: $t('schoolAdministration.pleaseOriginalCredits'),
                                        trigger: ['blur', 'change']
                                    }
                                ]"
                            >
                                <el-input
                                    type="number"
                                    min="0"
                                    max="100"
                                    :disabled="mode == 'AUDIT'"
                                    v-model="scope.row.oldCredit"
                                ></el-input>
                            </el-form-item>
                            <span v-else>{{ scope.row.oldCredit }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('schoolAdministration.operate')" fixed="right" v-if="mode !== 'VIEW' && mode !== 'AUDIT'">
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                v-if="!scope.row.status"
                                @click="oldCourseOperate('SAVE', scope.$index)"
                            >
                               {{$t('schoolAdministration.save')}}
                            </el-button>
                            <el-button
                                type="text"
                                v-else
                                @click="oldCourseOperate('EDIT', scope.$index)"
                            >
                                {{$t('schoolAdministration.edit')}}
                            </el-button>
                            <el-button
                                v-if="scope.$index"
                                type="text"
                                @click="oldCourseOperate('DEL', scope.$index)"
                            >
                                {{$t('schoolAdministration.delete')}}
                            </el-button>
                        </template>
                    </el-table-column>
                </edu-table>
                <el-row style="padding:16px 0">
                    <el-col span="12">
                        <h2><span style="color:#F56C6C;margin-right: 4px">*</span>{{$t('schoolAdministration.identifyCourses')}}</h2>
                    </el-col>
                    <el-col span="12" style="text-align:right" v-if="mode !== 'VIEW' && mode !== 'AUDIT'">
                        <span style="color:red;margin-right:16px" v-if="!applyParams.exchangeName">
                            {{$t('schoolAdministration.pleaseSelectExchangeNameFirst')}}
                        </span>
                        <el-button
                            type="primary"
                            :disabled="!applyParams.exchangeName"
                            @click="chooseCourse"
                        >
                             {{$t('schoolAdministration.chooseCourse')}}
                        </el-button>
                    </el-col>
                </el-row>
                <courseSelect
                    ref="courseSelect"
                    :visible="chooseDialog.visible"
                    :studentInfo="studentInfo"
                    @selectChange="selectCourses"
                    @close="courseDialogClose"
                ></courseSelect>
                <edu-table :data="applyParams.newCourseList" :selection="false" :pagination="false" class="course-table">
                    <el-table-column :label="$t('schoolAdministration.identifyCourseCode')" prop="courseCode"></el-table-column>
                    <el-table-column
                        :label="$t('schoolAdministration.identifyCourseName')"
                        prop="courseName"
                        min-width="140"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column :label="$t('schoolAdministration.creditRecognition')" prop="creidits"></el-table-column>
                    <el-table-column :label="$t('schoolAdministration.recognitionScore')" show-overflow-tooltip>
                        <template slot-scope="scope" v-if="mode !== 'ADD'">
                            <el-form-item
                                label-width="0"
                                :prop="`newCourseList[${scope.$index}].newCourseScore`"
                                :rules="[
                                    {
                                        required: !!scope.row.showBtnFlag,
                                        message: $t('schoolAdministration.pleaseSelectRecognitionScore'),
                                        trigger: ['blur', 'change']
                                    }
                                ]"
                            >
                            <!-- || !scope.row.showBtnFlag -->
                                <el-select
                                    v-model="scope.row.newCourseScore"
                                    :disabled="
                                        mode == 'VIEW'  || global.isStudent
                                    "
                                    :placeholder="$t('schoolAdministration.pleaseEnter')"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in options.scoreList"
                                        :key="item.scoreNum"
                                        :label="item.scoreName"
                                        :value="item.scoreNum"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column  :label="$t('schoolAdministration.cognizanceYearAndSemester')" width="200">
                        <template slot-scope="scope">
                            <el-form-item
                                label-width="0"
                                :prop="`newCourseList[${scope.$index}].identifyCalendarId`"
                                :rules="[
                                    {
                                        required: true,
                                        message: $t('schoolAdministration.pleaseSelectYearAndSemester'),
                                        trigger: ['blur', 'change']
                                    }
                                ]"
                            >
                                <el-select
                                    clearable
                                    :placeholder="$t('schoolAdministration.pleaseEnter')"
                                    :disabled="mode == 'VIEW' || mode == 'AUDIT'"
                                    v-model="scope.row.identifyCalendarId"
                                >
                                    <el-option
                                        v-for="item in options.calenderList"
                                        :key="item.calendarId"
                                        :label="item.calendarName"
                                        :value="item.calendarId"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('schoolAdministration.operate')" fixed="right" v-if="mode !== 'VIEW' && mode !== 'AUDIT'">
                        <template slot-scope="scope">
                            <el-button type="text" @click="deleteNewCourse(scope.$index)">
                                 {{$t('schoolAdministration.delete')}}
                            </el-button>
                        </template>
                    </el-table-column>
                </edu-table>
                <el-form-item
                    style="margin-left:32px"
                    :label="$t('schoolAdministration.applicationDescription')"
                    prop="applyDesc"
                    :rules="[{ required: false, message: $t('schoolAdministration.pleaseSelect'), trigger: 'blur' }]"
                >
                    <el-input
                        v-model="applyParams.applyDesc"
                        type="textarea"
                        style="width:60%;margin-top:16px"
                        maxlength="500"
                        :disabled="mode == 'AUDIT'"
                        :rows="4"
                        :placeholder="$t('schoolAdministration.pleaseEnterContent')"
                    ></el-input>
                </el-form-item>
                <el-row>
                    <h2>{{$t('schoolAdministration.supportingMaterials')}}</h2>
                    <el-form-item
                        ref="reportCard"
                        :label="$t('schoolAdministration.schoolReport')"
                        style="padding-left:32px"
                        prop="reportCard"
                        :rules="[
                            {
                                required: true,
                                message: $t('schoolAdministration.pleaseUploadYourTranscript'),
                                trigger: ['blur', 'change']
                            }
                        ]"
                    >
                        <el-upload
                            :headers="{
                                'X-Token': $store.state.session.sessionid
                            }"
                            :data="{
                                bucketname: 'face',
                                folderpath: 'file'
                            }"
                            action="/api/commonservice/obsfile/uploadfile"
                            :on-success="
                                (response, file, fileList) =>
                                    handlerSuccess(response, file, fileList, 'reportCard')
                            "
                            :on-remove="
                                (file, fileList) => handlerRemove(file, fileList, 'reportCard')
                            "
                            :before-upload="beforeUpload"
                            :on-preview="handlerPreRecord"
                            :on-error="handlerError"
                            :file-list="applyParams.reportCard"
                        >
                            <div style="display:-webkit-inline-box">
                                <el-button size="small" type="primary" :disabled="mode == 'AUDIT'">
                                    <i class="el-icon-upload el-icon--left"></i>
                                     {{$t('schoolAdministration.uploadAttachment')}}
                                </el-button>
                                <div slot="tip" class="el-upload__tip" style="margin: 2px 0 0 5px;">
                                     {{$t('schoolAdministration.uploadOnly')}}
                                </div>
                            </div>
                        </el-upload>
                    </el-form-item>
                    <el-form-item
                        :label="$t('schoolAdministration.other')"
                        style="padding-left:32px"
                        prop="reportCard"
                        :rules="[
                            {
                                required: false,
                                message: $t('schoolAdministration.pleaseUploadOtherAttachments'),
                                trigger: ['blur', 'change']
                            }
                        ]"
                    >
                        <el-upload
                            :headers="{
                                'X-Token': $store.state.session.sessionid
                            }"
                            :data="{
                                bucketname: 'face',
                                folderpath: 'file'
                            }"
                            action="/api/commonservice/obsfile/uploadfile"
                            :on-success="
                                (response, file, fileList) =>
                                    handlerSuccess(response, file, fileList, 'attachment')
                            "
                            :on-remove="
                                (file, fileList) => handlerRemove(file, fileList, 'attachment')
                            "
                            :before-upload="beforeUpload"
                            :on-error="handlerError"
                            :file-list="applyParams.attachment"
                            :on-preview="handlerPreAttach"
                        >
                            <div style="display:-webkit-inline-box">
                                <el-button size="small" type="primary" :disabled="mode == 'AUDIT'">
                                    <i class="el-icon-upload el-icon--left"></i>
                                     {{$t('schoolAdministration.uploadAttachment')}}
                                </el-button>
                                <div slot="tip" class="el-upload__tip" style="margin: 2px 0 0 5px;">
                                    {{$t('schoolAdministration.uploadOnly')}}
                                </div>
                            </div>
                        </el-upload>
                    </el-form-item>
                </el-row>
            </el-form>
            <el-row type="flex" justify="end" v-if="mode === 'ADD' || mode === 'EDIT'">
                <el-button @click="handleClick('CANCEL')">{{$t('schoolAdministration.cancel')}}</el-button>
                <el-button type="primary" @click="handleClick('SAVE')">{{$t('schoolAdministration.save')}}</el-button>
                <el-button type="primary" @click="handleClick('SUB')">{{$t('schoolAdministration.submit')}}</el-button>
            </el-row>
            <el-form
                label-suffix="："
                label-position="right"
                label-width="100px"
                ref="audit"
                :model="approvalInfo"
            >
                <template v-if="mode == 'AUDIT'">
                    <h2>{{$t('schoolAdministration.auditOpinion')}}</h2>
                    <el-form-item :label="$t('schoolAdministration.auditOpinion')" prop="content" style="padding-left:32px">
                        <el-input
                            type="textarea"
                            :rows="4"
                            resize="none"
                            v-model="approvalInfo.content"
                        ></el-input>
                    </el-form-item>
                    <div style="text-align:right">
                        <el-button type="danger" @click="handleClickAudit('DOWN')">{{$t('schoolAdministration.reject')}}</el-button>
                        <el-button type="primary" @click="handleClickAudit('BY')">{{$t('schoolAdministration.adopt')}}</el-button>
                    </div>
                </template>
            </el-form>
        </el-card>
        <!-- 审批进度 -->
        <el-card shadow="never" v-if="mode === 'VIEW' || mode === 'AUDIT'">
            <h2 class="title">{{$t('schoolAdministration.approvalProgress')}}</h2>
            <edu-table :order="false" :pagination="false" :selection="false" :data="auditList">
                <el-table-column :label="$t('schoolAdministration.time')">
                    <template slot-scope="scope">
                        {{ scope.row.time | formatDate }}
                    </template>
                </el-table-column>
                <el-table-column :label="$t('schoolAdministration.approvedBy')" prop="approvorName"></el-table-column>
                <el-table-column :label="$t('schoolAdministration.role')" prop="role"></el-table-column>
                <el-table-column prop="result" :label="$t('schoolAdministration.approvalResults')" width="120">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.result == 'COMMIT'" type="success">{{$t('schoolAdministration.submit')}}</el-tag>
                        <el-tag v-if="scope.row.result == 'Process'" type="success">{{$t('schoolAdministration.adopt')}}</el-tag>
                        <el-tag v-if="scope.row.result == 'End'" type="info">{{$t('schoolAdministration.finished')}}</el-tag>
                        <el-tag v-if="scope.row.result == 'Reject'" type="warning">{{$t('schoolAdministration.rejected')}}</el-tag>
                        <el-tag v-if="scope.row.result == 'Recall'" type="warning">{{$t('schoolAdministration.withdraw')}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    :label="$t('schoolAdministration.explain')"
                    prop="content"
                    show-overflow-tooltip
                ></el-table-column>
            </edu-table>
        </el-card>
    </div>
</template>

<script>
import filters from 'common/src/filters'
import UTILS from 'common/src/utils/utils'
import minxin from 'common/src/mixins/index.js'
import courseSelect from './component/courseSelect'
import baseInfo from './component/baseInfo'
import {
    canAuditOption,
    addExchangeInfo,
    checkProgress,
    getAcrossTermNum,
    getScopeTypeList,
    queryExchangelist,
    getTableList,
    updateContentApi
} from 'common/src/api/internationalExchanges/creditApplication'
import { selectApproFlow, approvalThrough, approvalReject } from 'common/src/api/approval'
export default {
    filters: {
        formatDate(date) {
            return filters.formatDate(date, 'yyyy/MM/dd hh:mm:ss')
        }
    },
    components: {
        courseSelect,
        baseInfo
    },
    mixins: [minxin],
    props: ['publicInfo'],
    data() {
        return {
            mode: 'ADD',
            type: 0, //0:学生自行申请，1：待申请
            lastPath: '',
            chooseDialog: {
                visible: false
            },
            applyParams: {
                id: '',
                studentId: '',
                studentName: '',
                exchangeName: '',
                oldCourseList: [
                    {
                        oldCourseName: '',
                        oldCourseScore: '',
                        oldCredit: '',
                        status: 0 //0:编辑 1：保存
                    }
                ],
                newCourseList: [],
                copyNewCourseList: [],
                applyDesc: '',
                reportCard: [],
                attachment: []
            },
            studentInfo: {},
            approvalInfo: {
                uid: '',
                no: '',
                content: '',
                dataProcess: [],
                approveAttachment: []
            },
            auditList: [],
            options: {
                exchangeList: [],
                calenderList: [],
                scoreList: []
            }
        }
    },
    mounted() {
        if (this.publicInfo && this.publicInfo.no) {
            this.getInfo();
            return;
        }
        let params = this.$route.query
        this.mode = params.mode
        if (params.type) this.type = params.type
        this.mode !== 'ADD' && this.assemb(params.data)
        //保存认定课程id字段，后台做更新使用
        if (this.applyParams.newCourseList.length > 0) {
            this.applyParams.copyNewCourseList = this.applyParams.newCourseList.map(item => {
                return {
                    id: item.id,
                    pid: item.pid
                }
            })
        }
        this.initExchangelist(params.studentInfo.studentId)
        this.applyParams.studentId = params.studentInfo.studentId
        this.applyParams.studentName = params.studentInfo.studentName
        this.studentInfo = params.studentInfo
        this.studentInfo.exchangeName = this.applyParams.exchangeName
        params.data && params.data.approvalId && this.getDetails(params.data.approvalId)
        this.applyParams.id && this.canAudit(this.applyParams.id)
    },
    watch: {
        'applyParams.exchangeName': function(val, oldVal) {
            if (val) {
                this.queryConstant()
                this.queryScoreTypeList()
            }
        }
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            vm.lastPath = from.path
        })
    },
    methods: {
        async updateContentfun() {
          var content=this.publicInfo.content;
          content=JSON.stringify(content);
          let params = {
                no: this.publicInfo.no,
                content:content
            };
            let { code, data } = await updateContentApi(params)
            if (code !== 200) return
        },
        getInfo() {
            let content, {applicantId, no, listApproveHistory, isApproveShow} = this.publicInfo;
            try {
                content  = JSON.parse(this.publicInfo.content);
            }catch(error){
                content = this.publicInfo.content;
            }
            this.approvalInfo.uid = applicantId;
            this.approvalInfo.no = no;
            this.auditList = listApproveHistory;
            //   case 'AUDIT':
            //     case 'VIEW':
            //         this.$router.push({
            //             path: 'UGIECreditDetail',
            //             query: {
            //                 data,
            //                 mode,
            //                 studentInfo: {
            //                     studentId: data.studentId,
            //                     grade: data.grade
            //                 }
            //             }
            //         })
            //         break
            this.mode = !isApproveShow ? 'AUDIT' : 'VIEW';
            //this.getSpecificInfo(content.id);
            this.setInfo(content);
        },
        setInfo(content = {}) {
            this.assemb(content);
            if (this.applyParams.newCourseList.length > 0) {
                this.applyParams.copyNewCourseList = this.applyParams.newCourseList.map(item => {
                    (item.courseCode = item.newCourseCode),
                    (item.courseName = item.newCourseName),
                    (item.creidits = item.newCredit);
                    return {
                        id: item.id,
                        pid: item.pid
                    }
                })
            }
            this.initExchangelist(content.studentId)
            this.studentInfo.studentId = content.studentId;
            this.studentInfo.exchangeName = content.exchangeName;
            this.studentInfo.grade = content.grade;
            this.applyParams.id && this.canAudit(content.id);
        },
        async getSpecificInfo(id) {
            let params = {
                pageNum_: 1,
                pageSize_: 20,
                condition: {
                    ids: [id],
                    calendarId: '',
                    queryType: '2',
                    status: ''
                }
            };
            let { code, data } = await getTableList(params);
            if (code !== 200) return;
            data.list.forEach(ele => {
                ele.newCourseList = ele.newCourseList || [];
                ele.newCourseList.forEach(item => {
                    (item.courseCode = item.newCourseCode),
                    (item.courseName = item.newCourseName),
                    (item.creidits = item.newCredit)
                })
            });
            this.setInfo(data.list && data.list[0]);
        },
        async canAudit(id) {
            let { code, data } = await canAuditOption(id)
            if (code !== 200) return
            this.$set(this.applyParams.newCourseList[0],'showBtnFlag',data.showBtnFlag)
        },
        async queryConstant() {
            let {
                code,
                data: { calenderList }
            } = await getAcrossTermNum({
                studentId: this.studentInfo.studentId,
                exchangeName: this.applyParams.exchangeName
            })
            if (code !== 200) return
            calenderList.forEach(item => (item.calendarId = item.calendarId.toString()))
            this.options.calenderList = calenderList
        },
        async queryScoreTypeList() {
            let { code, data } = await getScopeTypeList()
            if (code !== 200) return
            this.options.scoreList = data[0] && data[0].scoreDetail
        },
        async getDetails(id) {
            let { code, data } = await selectApproFlow(id)
            if (!code == 200) return
            let cont = data.content ? JSON.parse(data.content) : {}
            if (!cont) return
            //保存审核参数
            this.approvalInfo.uid = data.applicantId
            this.approvalInfo.no = data.no
            this.auditList = data && data.listApproveHistory
        },
        exchangeChange(val) {
            this.studentInfo.exchangesName = val
        },
        assemb(data) {
            for (let key in this.applyParams) {
                this.applyParams[key] = data[key]
                if (key == 'oldCourseList') {
                    this.applyParams[key].forEach(item => (this.$set(item, 'status', true)))
                } else if (key == 'attachment' || key == 'reportCard') {
                    this.applyParams[key] = JSON.parse(this.applyParams[key])
                }
            }
        },
        async initExchangelist(studentId) {
            let { code, data } = await queryExchangelist(studentId)
            if (code !== 200) return
            this.options.exchangeList = data.map((item, index) => {
                return {
                    label: item,
                    key: index,
                    value: item
                }
            })
        },
        addOldCourse() {
            let list = this.applyParams.oldCourseList
            let oldCourseChild = {
                oldCourseName: '',
                oldCourseScore: '',
                oldCredit: '',
                status: 0
            }
            list.push(oldCourseChild)
            this.applyParams.oldCourseList = list
        },
        oldCourseOperate(mode, index) {
            let list = this.applyParams.oldCourseList
            switch (mode) {
                case 'SAVE':
                    let obj = list[index]
                    if (obj.oldCourseName && obj.oldCourseScore && obj.oldCredit) {
                        list[index].status = !0
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '请检查当前行内容是否填写完整'
                        })
                    }
                    break
                case 'DEL':
                    list.splice(index, 1)
                    break
                case 'EDIT':
                    list[index].status = 0
                    break
            }
        },
        deleteNewCourse(index) {
            let list = this.applyParams.newCourseList
            list.splice(index, 1)
        },
        chooseCourse() {
            this.chooseDialog.visible = !this.chooseDialog.visiable;
            this.$nextTick(()=> {
                this.$refs['courseSelect'].queryCoursesData && this.$refs['courseSelect'].queryCoursesData();
            })
        },
        courseDialogClose() {
            this.chooseDialog.visible = false;
        },
        selectCourses(courses) {
            if (this.applyParams.newCourseList.length === 0) {
                this.applyParams.newCourseList = courses
            } else {
                this.applyParams.newCourseList = courses.map((item, index) => {
                    return Object.assign(this.applyParams.copyNewCourseList[index] || {}, item)
                })
            }
            this.chooseDialog.visible = false;
        },
        //移除文件回调
        handlerRemove(file, fileList, mode) {
            let list = this.applyParams[mode]
            let index = list.findIndex(item => item.uid == file.uid)
            list.splice(index, 1)
            this.applyParams[mode] = list
        },
        //上传文件成功回调
        handlerSuccess(response, file, fileList, mode) {
            let responseCode = response.code
            if (responseCode === 200) {
                this.applyParams[mode].push({
                    name: file && file.name,
                    url: file.response.data[file.name] && file.response.data[file.name].objectkey,
                    path: file.response.data[file.name] && file.response.data[file.name].objectkey
                })

                let len = this.applyParams['reportCard']
                if (len.length > 0) this.$refs['reportCard'].clearValidate()
            } else {
                this.$message({
                    message: '文件列名错误或文件为空！',
                    type: 'error'
                })
            }
        },
        //上传文件失败回调
        handlerError(response, file, fileList) {
            this.$message({
                message: '上传失败！',
                type: 'error'
            })
        },
        //上传文件类型校验
        beforeUpload(file) {
            return UTILS.checkFile(
                file,
                {
                    name: '.jpg,.png,.gif,.doc,.docx,.xlsx,.xls,.pdf',
                    size: '5'
                },
                this
            )
        },
        assembRequestData() {
            let params = _.cloneDeep(this.applyParams)
            params.newCourseList.forEach(item => {
                ;(item.newCourseCode = item.courseCode),
                    (item.newCourseName = item.courseName),
                    (item.newCredit = item.creidits)
            })
            params.reportCard = JSON.stringify(params.reportCard)
            params.attachment = JSON.stringify(params.attachment)
            return params
        },
        async saveApply() {
            let { code, data } = await addExchangeInfo(this.assembRequestData())
            if (code !== 200) return
            this.$message({
                type: 'success',
                message: '保存成功'
            })
            this.goBack()
        },
        goBack() {
            this.$store.commit('delete_tabs', this.$route.path)
            this.$router.go(-1)
        },
        submitApply() {
            let params = this.assembRequestData()
            params.type = this.type
            if(!params.oldCourseList||params.oldCourseList ==null || params.oldCourseList.length==0){
                this.$message({
                    type: 'error',
                    message: '原课程信息不能为空'
                })
                return
            }
            if(!params.newCourseList||params.newCourseList ==null ||params.newCourseList.length ==0 ){
                this.$message({
                    type: 'error',
                    message: '认定课程信息不能为空'
                })
                return
            }
            if(!params.reportCard||params.reportCard ==null || params.reportCard ==""){
                this.$message({
                    type: 'error',
                    message: '成绩单不能为空'
                })
                return
            }
            checkProgress(params).then(res=>{
                if(res.code===200){
                    this.$message({
                        type: 'success',
                        message: '提交成功'
                    })
                    this.goBack()
                }
            })
        },
        handleClick(mode) {
            if (mode !== 'CANCEL') {
                this.$refs['application'].validate(valid => {
                    if (valid) {
                        switch (mode) {
                            case 'SAVE':
                                this.saveApply()
                                break
                            case 'SUB':
                                this.submitApply()
                                break
                        }
                    } else {
                        return false
                    }
                })
            } else {
                Object.assign(this.$data, this.$options.data())
                this.goBack()
            }
        },
        async submitAudit(fn, mode) {
            let { code, data } = await fn
            if (code !== 200) return
            this.$message({
                type: 'success',
                message: mode == 'BY' ? '审批通过成功' : '审批驳回成功'
            })
            this.updateContentfun();
            this.goBack()
        },
        handlerPreRecord(file) {
            window.location.href = '/api/commonservice/obsfile/downloadfile?objectkey=' + file.url
        },
        handlerPreAttach(file) {
            window.location.href = '/api/commonservice/obsfile/downloadfile?objectkey=' + file.url
        },
        handleClickAudit(mode) {
            let params = this.approvalInfo
            params.dataProcess = this.applyParams.newCourseList
            switch (mode) {
                case 'BY':
                    this.$refs['application'].validate(valid => {
                        if (valid) {
                            if (this.publicInfo && this.publicInfo.no) {
                              for(var i=0;i<this.applyParams.newCourseList.length;i++){
                                if (!this.applyParams.newCourseList[i].newCourseScore) {
                                this.$message({
                                    type: 'warning',
                                        message: this.$t('schoolAdministration.pleaseSelectRecognitionScore'),
                                    })
                                    return
                                }
                              }
                          }
                          this.submitAudit(approvalThrough(params), mode)
                        } else {
                            return false
                        }
                    })
                    break
                case 'DOWN':

                    if (!this.approvalInfo.content) {
                        this.$message({
                            type: 'warning',
                            message: '需要输入审核意见'
                        })
                        return
                    }
                    this.submitAudit(approvalReject(params), mode)
                    break
            }
        }
    }
}
</script>

<style lang="scss" scoped>
    .course-table ::v-deep  .el-form-item{
        margin-bottom: 0;
    }
</style>
